package com.leoman.plz_p.views.mine;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.CenterCrop;
import com.leoman.plz_p.R;
import com.leoman.plz_p.interfaces.PersonalInfoView;
import com.leoman.plz_p.module.bean.RefreshUser;
import com.leoman.plz_p.module.bean.User;
import com.leoman.plz_p.presenter.PersonalInfoPresenter;
import com.leoman.plz_p.utils.FileUtils;
import com.leoman.plz_p.utils.UserHelper;
import com.leoman.plz_p.weidget.ChooseAvatarPopupWindow;
import com.leoman.plz_p.weidget.NavBar;
import com.leoman.plz_p.weidget.RoundedTransformationBuilder;

import java.io.File;
import java.util.List;

import butterknife.Bind;
import butterknife.OnClick;
import cn.addapp.pickers.entity.City;
import cn.addapp.pickers.entity.County;
import cn.addapp.pickers.entity.Province;
import cn.addapp.pickers.util.AddressPickTask;
import cn.com.corelib.base.BaseActivity;
import cn.com.corelib.utils.ToastMgr;
import cn.com.corelib.utils.rxbus.RxBus;
import cn.finalteam.galleryfinal.FunctionConfig;
import cn.finalteam.galleryfinal.GalleryFinal;
import cn.finalteam.galleryfinal.model.PhotoInfo;
import top.zibin.luban.CompressionPredicate;
import top.zibin.luban.Luban;
import top.zibin.luban.OnCompressListener;

/**
 * Created by guoh on 2018/9/2.
 */
public class PersonalInfoActivity extends BaseActivity<PersonalInfoView,PersonalInfoPresenter> implements PersonalInfoView{
    @Bind(R.id.nav)
    NavBar nav;
    @Bind(R.id.iv_head)
    ImageView ivHead;
    @Bind(R.id.tv_nick_name)
    TextView tvNickName;
    @Bind(R.id.tv_level)
    TextView tvLevel;
    @Bind(R.id.tv_school)
    TextView tvSchool;
    @Bind(R.id.tv_school_number)
    TextView tvSchoolNumber;
    @Bind(R.id.tv_class)
    TextView tvClass;
    @Bind(R.id.tv_address)
    TextView tvAddress;
    @Bind(R.id.tv_id_card)
    TextView tvIdCard;
    @Bind(R.id.tv_tel)
    TextView tvTel;
    @Bind(R.id.ll_head)
    LinearLayout llHead;
    @Bind(R.id.ll_nick_name)
    LinearLayout llNickName;
    @Bind(R.id.ll_level)
    LinearLayout llLevel;
    @Bind(R.id.ll_school)
    LinearLayout llSchool;
    @Bind(R.id.ll_school_number)
    LinearLayout llSchoolNumber;
    @Bind(R.id.ls_class)
    LinearLayout llClass;
    @Bind(R.id.ll_address)
    LinearLayout llAddress;
    @Bind(R.id.ll_id_card)
    LinearLayout llIdCard;
    @Bind(R.id.ll_tel)
    LinearLayout llTel;

    public static final int REQUEST_CAMERA = 1;
    public static final int REQUEST_GALLERY = 2;

    private ChooseAvatarPopupWindow window;

    private String headImageFile;

    public static Intent getLaunchIntent(Context context) {
        Intent intent = new Intent(context, PersonalInfoActivity.class);
        return intent;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.ac_personal_info;
    }

    @Override
    protected void init(Bundle savedInstanceState) {
        nav.setTitle("个人信息");
        nav.setRightTextAndImage(0, "保存", new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (headImageFile!=null){
                    uploadHead(headImageFile);
                }else {
                    getPresenter().editUser(UserHelper.getSavedUser().getHeadimg(), getText(tvNickName), UserHelper.getSavedUser().getAddress(),UserHelper.getSavedUser().getAddressName(), getText(tvIdCard), getText(tvTel));
                }
            }
        });
        setUserData();


    }

    private void setUserData(){
        User user=UserHelper.getSavedUser();
        if (!TextUtils.isEmpty(user.getHeadimg())) {
            Glide.with(getViewContext()).load(user.getHeadimg()).centerCrop().transform(new CenterCrop(getViewContext()), new RoundedTransformationBuilder().oval(true).build(getViewContext())).into(ivHead);
        }
        tvNickName.setText(user.getNickname());
        tvLevel.setText(user.getLevelName()+"");
        tvSchool.setText(user.getSchool());
        tvSchoolNumber.setText(user.getStudentId());
        tvClass.setText(user.getGradeName());
        tvAddress.setText(user.getAddressName());
        tvIdCard.setText(user.getIdentity());
        tvTel.setText(user.getPhone());
    }

    @Override
    protected PersonalInfoPresenter createPresenter() {
        return new PersonalInfoPresenter();
    }


    @OnClick({R.id.iv_head,R.id.ll_nick_name, R.id.ll_address, R.id.tv_id_card, R.id.tv_tel})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_head:
                window = new ChooseAvatarPopupWindow(PersonalInfoActivity.this);
                window.setOnTypeChosenListener(new ChooseAvatarPopupWindow.OnTypeChosenListener() {
                    @Override
                    public void onCamera() {
                        GalleryFinal.openCamera(REQUEST_CAMERA, setupFunctionConfig(),
                                new GalleryFinal.OnHanlderResultCallback() {

                                    @Override
                                    public void onHanlderSuccess(int requestCode, List<PhotoInfo> resultList) {
                                        PhotoInfo info = resultList.get(0);
                                        Glide.with(getViewContext()).load(info.getPhotoPath()).centerCrop().transform(new CenterCrop(getViewContext()), new RoundedTransformationBuilder().oval(true).build(getViewContext())).into(ivHead);
                                        headImageFile=info.getPhotoPath();
                                    }

                                    @Override
                                    public void onHanlderFailure(int requestCode, String errorMsg) {}
                                });
                    }

                    @Override
                    public void onGallery() {
                        GalleryFinal.openGalleryMuti(REQUEST_GALLERY, 1,
                                new GalleryFinal.OnHanlderResultCallback() {

                                    @Override
                                    public void onHanlderSuccess(int requestCode, List<PhotoInfo> resultList) {
                                        if (resultList!=null&&resultList.size()>0) {
                                            Glide.with(getViewContext()).load(resultList.get(0).getPhotoPath()).centerCrop().transform(new CenterCrop(getViewContext()), new RoundedTransformationBuilder().oval(true).build(getViewContext())).into(ivHead);
                                            headImageFile = resultList.get(0).getPhotoPath();
                                        }
                                    }

                                    @Override
                                    public void onHanlderFailure(int requestCode, String errorMsg) {}
                                });
                    }
                });
                window.showAtBottom(view);
                break;
            case R.id.ll_nick_name:
                startActivity(CommonInputInfoActivity.getLaunchIntent(getViewContext(), 0));
                break;
            case R.id.ll_address:
                AddressPickTask task = new AddressPickTask(this);
                task.setHideProvince(false);
                task.setHideCounty(false);
                task.setCallback(new AddressPickTask.Callback() {
                    @Override
                    public void onAddressInitFailed() {
                        showToast("数据初始化失败");
                    }

                    @Override
                    public void onAddressPicked(Province province, City city, County county) {
                        if (county == null) {
                            //showToast(province.getAreaName() + city.getAreaName());
                        } else {
                            tvAddress.setText(province.getAreaName()+city.getAreaName()+county.getAreaName());
                            User user=UserHelper.getSavedUser();
                            user.setAddressName(province.getAreaName()+city.getAreaName()+county.getAreaName());
                            user.setAddress(county.getCityId());
                            UserHelper.saveUser(user);
                        }
                    }
                });
                task.execute("湖北省", "武汉市", "洪山区");
                break;
            case R.id.tv_id_card:
                startActivity(CommonInputInfoActivity.getLaunchIntent(getViewContext(), 1));
                break;
            case R.id.tv_tel:
                startActivity(CommonInputInfoActivity.getLaunchIntent(getViewContext(), 2));
                break;
        }
    }

    @Override
    public void editSuccess() {
        ToastMgr.show("修改成功");
        RxBus.getDefault().send(new RefreshUser());
        finish();
    }

    @Override
    public void obtainUploadImageSuccess(String path) {
        User user=UserHelper.getSavedUser();
        user.setHeadimg(path);
        UserHelper.saveUser(user);
        getPresenter().editUser(UserHelper.getSavedUser().getHeadimg(), getText(tvNickName),  UserHelper.getSavedUser().getAddress(),UserHelper.getSavedUser().getAddressName(), getText(tvIdCard), getText(tvTel));
    }

    private FunctionConfig setupFunctionConfig(int maxSize) {
        return new FunctionConfig.Builder()
                .setEnableCamera(false)
                .setEnableEdit(false)
                .setEnablePreview(false)
                .setEnableRotate(false)
                .setEnableCrop(false)
                .setMutiSelectMaxSize(maxSize)
                .build();
    }

    private FunctionConfig setupFunctionConfig() {
        return setupFunctionConfig(1);
    }

    private void uploadHead(String head){
        Luban.with(getViewContext())
                .load(head)
                .ignoreBy(100)
                .setTargetDir(FileUtils.getMediaPath())
                .filter(new CompressionPredicate() {
                    @Override
                    public boolean apply(String path) {
                        return !(TextUtils.isEmpty(path) || path.toLowerCase().endsWith(".gif"));
                    }
                })
                .setCompressListener(new OnCompressListener() {
                    @Override
                    public void onStart() {

                    }

                    @Override
                    public void onSuccess(File file) {
                        getPresenter().uploadUserHead(file);
                    }

                    @Override
                    public void onError(Throwable e) {

                    }
                }).launch();
    }
}
